<template>
  <div class="flex flex-col h-screen">
    <!-- 播放器  'playEnd', 'playStart' -->
    <playView
      :fileId="fileId"
      @playEnd="handlePlayComplete"
      @playStart="handlePlayStart"
    />
    <!-- 内容 -->
    <div ref="content" class="flex-auto flex flex-col overflow-y-auto">
      <div class="flex flex-col flex-auto p-4">
        <h2 class="text-[16px] mb-6 font-bold">
          {{ currentItem?.chapterName || "" }}
        </h2>
        <div>
          <div
            class="flex flex-row items-center p-3 bg-gradient-to-br from-[#F3F8FF] rounded-md to-[transparent]"
          >
            <img class="w-[24px] h-[24px] mr-2" :src="dataIcons.pageTitleIcon" />
            <h3 class="font-bold text-[16px]">知识点</h3>
          </div>
        </div>
        <markdown
          v-ai-tip="'bottom-right'"
          class="mt-3 box-border"
          :content="cp_knowledgePoint"
        />
      </div>
    </div>

    <!-- 底部工具条 -->
    <div class="w-full pb-safe shadow-inner">
      <div class="flex flex-row items-center justify-between px-[70px] py-4">
        <div class="flex flex-col items-center clickable" @click="onClickPreviousItem">
          <van-icon
            name="back-top"
            :color="isPrevDisabled ? '#BFBFBF' : '#333'"
            class="-rotate-90"
          />
          <p :class="`text-[12px] ${isPrevDisabled ? 'text-[#BFBFBF]' : 'text-[#333]'}`">
            上一个
          </p>
        </div>

        <div class="flex flex-col items-center clickable" @click="onItemClick(item)">
          <img :src="dataIcons.menuCourse" class="filter grayscale" alt="" />
          <p class="text-[12px]">目录</p>
        </div>

        <div class="flex flex-col items-center clickable" @click="onClickNextItem">
          <van-icon
            name="back-top"
            :color="isNextDisabled ? '#BFBFBF' : '#333'"
            class="rotate-90"
          />
          <p :class="`text-[12px] ${isNextDisabled ? 'text-[#BFBFBF]' : 'text-[#333] '}`">
            下一个
          </p>
        </div>
      </div>
    </div>

    <van-popup
      v-model:show="showMenu"
      :overlay="false"
      position="bottom"
      closeable
      safe-area-inset-bottom
      :style="{ height: `${popupHeight + 'px'}` }"
    >
      <div class="h-full flex-col overflow-y-auto">
        <h2 class="pt-3 ml-5 text-[14px]">目录</h2>
        <courseList
          class="mt-4 flex-auto"
          @clickItem="handleClickItem"
          :currentFileId="fileId"
        />
      </div>
    </van-popup>
  </div>
</template>

<script>
import playView from "../components/videoPlayView.vue";
import markdown from "@/components/markdown.vue";
import courseList from "../components/courseList.vue";
import icons from "@/icons/svg/minute/index";
import { mapState, mapActions } from "pinia";
import { useStudyStore } from "@/store";

export default {
  name: "StudyDetail",
  components: {
    playView,
    courseList,
    markdown,
  },
  mounted() {
    console.log("onMounted : ", this.$route);
    const { confId, fileId } = this.$route.query;
    this.fileId = fileId;
    if (!this.courseData) {
      this.getData(confId);
    } else {
      this.setDefaultFileId();
    }
  },
  data() {
    return {
      dataIcons: icons,
      showMenu: false,
      fileId: "",
      popupHeight: 0,
      content:
        "## 知识点一会议开始\n李东昆首先提出了行动力的概念，并介绍了之前合作的情况。他强调了顾问在临时解决方案中的作用，并提到了向东老师和郑州团队的参与。接着，李东昆详细介绍了学习平台的各个方面，包括但不限于：",
    };
  },

  methods: {
    ...mapActions(useStudyStore, {
      getUserkngAction: "getUserkngAction",
      updateCourseStudyStatusAction: "updateCourseStudyStatusAction",
    }),

    async getData(confId) {
      await this.getUserkngAction(confId);
      this.setDefaultFileId();
    },
    onItemClick() {
      const contentElement = this.$refs.content;
      const rect = contentElement.getBoundingClientRect();
      this.popupHeight = window.innerHeight - rect.top;
      this.showMenu = true;
    },

    setDefaultFileId() {
      if (!this.fileId || this.fileId?.length == 0) {
        this.fileId = this.courseFlatList[0]?.fileId || "";
        console.log("fileId is null, set default fileId: ", this.fileId);
      }
    },

    onClickPreviousItem() {
      if (this.isPrevDisabled) return;
      const currentIndex = this.courseFlatList.findIndex(
        (item) => item.fileId === this.fileId
      );
      this.fileId =
        currentIndex < this.courseFlatList.length - 1
          ? this.courseFlatList[currentIndex - 1].fileId
          : null;
    },

    onClickNextItem() {
      if (this.isNextDisabled) return;
      const currentIndex = this.courseFlatList.findIndex(
        (item) => item.fileId === this.fileId
      );
      console.log("currentIndex: ", this.courseFlatList, currentIndex, this.fileId);
      this.fileId =
        currentIndex < this.courseFlatList.length - 1
          ? this.courseFlatList[currentIndex + 1].fileId
          : null;
    },

    // 处理播放完成
    handlePlayComplete() {
      this.updateCourseStudyStatusAction(this.cp_PackageId, this.currentItem.id, 1);
      // 如果已经是最后一个则不用跳转
      if (this.isNextDisabled) return;
      let currentIndex = this.courseFlatList.findIndex(
        (item) => item.fileId === this.fileId
      );

      const findNextItemVideo = (tempIndex) => {
        // 如果已经是最后一个则不用跳转
        if (tempIndex >= this.courseFlatList.length - 1) {
          return null;
        }
        const nextItem = this.courseFlatList[tempIndex + 1];
        // 已经学习完成的则跳过
        if (nextItem.status === 2) {
          tempIndex++;
          return findNextItemVideo(tempIndex);
        }
        return nextItem.fileId;
      };

      const nextItemFileId = findNextItemVideo(currentIndex);
      if (nextItemFileId) {
        this.fileId = nextItemFileId;
      }
    },

    // 处理开始播放
    handlePlayStart() {
      this.updateCourseStudyStatusAction(this.cp_PackageId, this.currentItem.id, 0);
    },

    // 处理点击目录item
    handleClickItem(item) {
      this.currentItem = item;
      this.fileId = item.fileId;
      this.showMenu = false;
    },
  },

  computed: {
    ...mapState(useStudyStore, {
      courseData: "courseData",
      courseFlatList: "courseFlatList",
    }),

    // 当前课程包id
    cp_PackageId() {
      return this.courseData.id;
    },

    currentItem() {
      return this.courseFlatList.find((item) => item.fileId === this.fileId);
    },

    currentIndex() {
      return this.courseFlatList.findIndex((item) => item.fileId === this.fileId);
    },

    isPrevDisabled() {
      return this.currentIndex <= 0;
    },

    isNextDisabled() {
      return this.currentIndex >= this.courseFlatList.length - 1; // 如果当前索引大于等于最后一个，禁用下一个
    },

    cp_knowledgePoint() {
      return this.currentItem?.knowledgePoint.replace(/\n/g, "<br>");
    },
  },
};
</script>

<style lang="less" scoped>
.mbody {
  overflow-x: hidden;
  box-sizing: border-box;

  :deep p {
    margin: 8px 0;
    color: #262626;
    font-size: 14px;
    line-height: 26px;
  }

  :deep ol {
    display: block;
    list-style-type: decimal;
    padding-inline-start: 20px;
    unicode-bidi: isolate;
    margin-left: 12px;
    line-height: 26px;

    li {
      list-style-type: decimal;
      color: #262626;
      line-height: 26px;
      font-size: 14px;
      margin-bottom: 4px;
    }
  }
}
</style>
